import { defineStore } from "pinia";
import type {AddressListAddress} from 'vant'
import { addDingdan,removeGouwu ,getDingdan} from "@/api/dingdan";
type state = {
    dataList:gouwu[],
    dataRess:AddressListAddress,
    dingdanData:obj[]
}
export const useDingdan = defineStore(
    'dingdan',
    {
        state:():state=>{
            return {
                // 选中商品数据
                dataList:[],
                // 选择地址数据
                dataRess:{} as AddressListAddress,
                // 获取订单信息
                dingdanData:[] 
            }
        },
        getters:{},
        actions:{
            
            changeData(arr:gouwu[]){
                this.dataList = arr
            },
            changeRess(obj:AddressListAddress){
                this.dataRess = obj
            },
            removeRess(){
                this.dataRess = {} as AddressListAddress
            },
            async fetchAdd(){
                // 添加订单请求
                let res = await addDingdan(localStorage.getItem("userId") as string);
                console.log(res);
                // 删除选中的购物车数据
                let res2 = await removeGouwu(localStorage.getItem("userId") as string);
                console.log(res2);
                
            },
            async fetchGet(){
                let res:dataObj[] = (await getDingdan(localStorage.getItem("userId") as string)).data;
                this.dingdanData = [];
                res.forEach(item=>{
                    if(this.dingdanData.some(i=>i.time == item.time)){
                        let index = this.dingdanData.findIndex(i=>i.time == item.time);
                        this.dingdanData[index].children.push(item);
                    }else{
                        this.dingdanData.push({
                            time:item.time,
                            children:[item]
                        })
                    }
                })
                console.log(this.dingdanData);
                
            },

            findData(time:string){
                return this.dingdanData.find(item=>item.time == time)
            }
        },
    }
)